<template>
  <div class="dataContent">
    <dateSlide :dateType="timeType" :startTime="beginTime" @dateChange="dateChange" />
    <div class="loading" v-if="!loading">
      <van-loading size="36px"></van-loading>
      <p>加载中...</p>
    </div>
    <div class="content" v-show="userDataList">
      <div class="dataList">
        <HeadingLine name="数据总览" />
        <div class="data-card">
          <div class="item-card" v-for="(item, index) in userDataList" :key="index">
            <p class="number blue">{{ item.num | numberToK }}</p>
            <p class="text-min">{{ item.title }}</p>
          </div>
        </div>
      </div>
      <div class="dataList" style="background: #fff;" v-if="clientDataList.length">
        <HeadingLine name="客户数据" />
        <div class="data-card">
          <div class="item-card" v-for="(item, index) in clientDataList" :key="index">
            <p class="number block">{{ item.num | numberToK }}</p>
            <p class="text-min">{{ item.title }}</p>
          </div>
        </div>
        <div class="line"></div>
      </div>
      <div class="charts" v-if="dataSource">
        <HeadingLine name="客户数据" />
        <div class="bar-chart" v-for="(item, index) in dataSource" :key="item.key">
          <h4 class="chart-title">{{ item.title }}</h4>
          <v-chart
            :height="220"
            :data="item.chartData"
            prevent-render
            @on-render="renderChart"
            >
            <v-bar />
          </v-chart>
        </div>
      </div>
      <div class="line" v-if="dataSource"></div>
      <div class="progress-box" ref="progressType">
        <HeadingLine name="楼盘数据" />
        <div v-if="progressList">
          <div class="progressList" v-for="list in progressList" :key="list.key">
            <h4 class="progress-title" :style="{color: list.color}">{{ list.title }}</h4>
            <progressed 
              v-for="(item,index) in list.progress"
              :key="index"
              :Info="item"
            />
          </div>
        </div>
        <div class="notData inner" v-else>
          <div class="image-notData floor-empty"></div>
          <p class="text">您还未开通楼盘哦</p>
        </div>
      </div>
    </div>
    <div class="notData " v-show="loading && !userDataList">
      <div class="image-notData data-empty"></div>
      <p class="text">暂无数据</p>
    </div>
  </div>
</template>
<script>
import dynamicsService from 'SERVICE/dynamicsService'
import { VChart, VBar } from '@/components/Vchart'
import { debounce, isEmpty } from 'lodash'
import progressed from './progress'
import HeadingLine from './HeadingLine'
import dateSlide from './dateSlide'

const userDataList = [
  { title: '楼盘浏览', num:0 },
  { title: '楼盘分享', num: 0 },
  { title: '文章浏览', num: 0 },
  { title: '名片浏览', num: 0 }
]

let clientDataList = [
  { title: '新增客户', num: 0 },
  { title: '沟通客户', num: 0 },
  { title: '报备客户', num: 0 },
  { title: '', num: '' },
]

export default {
  props: {
    timeType: {
      type: Number,
      default: 0
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      beginTime: '',
      loading: false,
      chartCount: 0,
      dataSource: null,
      progressList: null,
      isStart: false,
      userDataList: null,
      clientDataList: this.timeType ? [] : clientDataList
    }
  },
  components: {
    VChart,  
    VBar,
    HeadingLine,
    dateSlide,
    progressed
  },
  created() {
    let { beginTime } = this.$route.query
    if (beginTime) this.beginTime = beginTime
    // this.initData()
  },
  mounted() {
    this.debounceScroll = debounce(this.handleScroll, 200, { 'maxWait': 500 })
    window.addEventListener('scroll', this.debounceScroll, true)
  },
  methods: {
    // initData() {
    //   let type = this.timeType
    //   this.getChartsData(type, '2019-06-01', '2019-06-07')
    // },
    dateChange(startTime, endTime = '', bool) {  
      this.isStart = false
      this.chartCount = 0
      if (bool) {
        this.loading = false
      }
      this.getChartsData(this.timeType, startTime, endTime)
    },
    async getChartsData(type, start, end) {
      let res = await dynamicsService.getDataStatsByDate(type, start, end)
      if (isEmpty(res)) {
        this.userDataList = null
        this.loading = true
        return false
      }
      let str = type === 1 ? '周' : '月'
      let key = new Date().getTime()
      let newClientNum = res.newClientNum ? `(+${ res.newClientNum })` : ''
      const dataSource = [
        { title: `本${str}新增客户${ newClientNum }`, chartData: res.newClientList, color: "l(90) 0:#1993FF 1:#007AE6", key: key+=1 },
        { title: `本${str}沟通客户`, chartData: res.comClientList, color: "l(90) 0:#9DE686 1:#29CC2D", key: key+=2 },
        { title: `本${str}报备客户`, chartData: res.reportClientList, color: "l(90) 0:#A573FF 1:#645AFF", key: key+=3 },
      ]
      const progressList = [
        { title: '浏览量排名', progress: res.linkerScanNumList, key: 0 , color: '#007AE6', bgColor: 'linear-gradient(to right, #007AE6, #1993FF)' },
        { title: '分享量排名', progress: res.linkerShareNumList, key: 1, color: '#1A3CE6', bgColor: 'linear-gradient(to right, #2E4DE6, #1739E6)' },
      ]
      const userDataList = [
        { title: '楼盘浏览', num: res.linkerScanNum },
        { title: '楼盘分享', num: res.linkerShareNum },
        { title: '文章浏览', num: res.articleScanNum },
        { title: '名片浏览', num: res.cardScanNum }
      ]
      const clientDataList = [
        { title: '新增客户', num: res.newClientNum },
        { title: '沟通客户', num: res.comClientNum },
        { title: '报备客户', num: res.reportClientNum },
        { title: '', num: '' },
      ]
      this.setProgress(progressList)
      if (res.newClientList) {
        this.dataSource = dataSource
      } else {
        this.clientDataList = clientDataList
      }
      if (res.linkerScanNumList && res.linkerScanNumList.length) {
        this.progressList = progressList
      } else {
        this.progressList = null
      }
      this.userDataList = userDataList
      this.loading = true
      window.setTimeout(() => {
        this.handleScroll()
      }, 0)
    },
    setProgress(progressList) {
      let MaxArray = []
      progressList.forEach(list => {
        MaxArray.push(list.progress.map(item => item.num))
      })
      MaxArray = [].concat.apply([], MaxArray)
      let max = Math.max.apply(null, MaxArray)
      max = !max ? 1 : max
      progressList.forEach((list, index) => {
        let color = list.color
        list.progress && list.progress.forEach(item => {
          item.color = color
          item.start = false
          item.scale = (item.num/max*100) + '%'
        })
      })
    },
    handleScroll() {
      if (this.isStart || !this.progressList) return false
      let element = this.$refs.progressType
      const el = document.querySelector('.router-view')
      let scrollTop = el.scrollTop
      let offsetTop = element.offsetTop
      let height = document.body.clientHeight - 100
      if ((offsetTop - scrollTop) < height) {
        this.isStart = true
        this.progressList.forEach(list => {
          list.progress && list.progress.forEach(item => {
            item.start = true
          })
        })
      }
    },
    renderChart({ chart, chartData }) {
      var originDates = [];
      var firstDayArr = [];
      let data = chartData
      let chartCount = this.chartCount
      this.chartCount+=1
      data.forEach(function(obj) {
        obj.count = 100
        originDates.push(obj.name)
        if (obj.first) {
          firstDayArr.push(obj);
        }
      });
      let maxArray = data.map(item => item.num)
      let max = Math.max.apply(null, maxArray)
      max = max < 10 ? 12 : max
      // data.push({name: '2019-06-13', count: 100, num: 20 })
      chart.source(data, {
        name: {
          type: 'timeCat',
          tickCount: 6,
          values: originDates,
          mask: 'MM-DD'
        },
        num: {
          min: 0,
          max: max,
          tickCount: 5
        }
      });
      // 设置横坐标,日期显示为周日期
      let weeks = ['周一', '周二', '周三', '周四', '周五', '周六', '周日',]
      chart.axis('name', {
        tickLine: {
          length: 4,
          // stroke: '#cacaca'
        },
        label: function label(text, index, total){
          if (total === 7) {
            return {
              text: weeks[index]
            }
          }
          return {
            text: text
          // fill: '#cacaca'
          }
        },
        line: {
          top: true
        }
      });

      function formatNumber(n) {
        return String(Math.floor(n * 100) / 100).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      }
      const getChartColor = (index) => {
        let color = this.dataSource[index].color
        return color
      }

      // 设置纵坐标，不让纵坐标显示为0以下的负数
      let isNegative = false
      chart.axis('num', {
        position: 'left',
        // label: function label(text, index) {
          // let val = Number(text)
          // if (!isNegative && val < 0) {
          //   isNegative = true
          // }
          // if (isNegative) {
          //   val +=1
          // }
          // if (val < index) {
          //   val = index
          // }
          // return {
            // text: text,
            // fill: '#cacaca'
          // };
        // },
        // line: {
        //   lineWidth: 1,
        //   stroke: '#cacaca',
        //   top: true
        // },
        // tickLine: {
        //   lineWidth: 1,
        //   stroke: '#ccc',
        //   length: 5,// 刻度线长度
        // }, // 坐标点对应的线，null 不显示，图形属性
        grid: null
      });
     
      chart.tooltip({
        showTitle: false,
        showItemMarker: false,
        showTooltipMarker: false,
        // // 是否显示辅助线
        showCrosshairs: true,
        background: {
          radius: 4,
          fill: getChartColor(chartCount),
          padding: [5]
        },
        crosshairsStyle: {
          stroke: 'rgba(0, 0, 0, 0.25)',
          lineWidth: 1
        },
        // tooltipMarkerStyle: {
        //   fill: 'red',
        //   fillOpacity: 0.2
        // },
        onShow(ev) {
          var items = ev.items;
          items[0].name = null
          items[1].name = null
          let title = items[0].title
          let arr = title.split("-")
          title = arr[0] + "月" + arr[1] + "日"
          items[0].value = title + "   |"
          items[1].value = items[1].value + "人"
        }
      });
      let radius = chartData.length > 7 ? 3 : 5
      let size = chartData.length > 7 ? 6 : 8
      chart.axis('count', false)
      chart.interval().position('name*count').color('#F2F3F5').size(size).animate(false).style({
        radius: [radius, radius, 0, 0]
      })
      chart.interval().position('name*num').color(getChartColor(chartCount)).size(size).style({
        radius: [radius, radius, 0, 0]
      })
      
      // 设置时间间隔显示
      // firstDayArr.forEach(function(obj) {
      //   chart.guide().line({
      //     top: false,
      //     start: [obj.name, 'min'],
      //     end: [obj.name, 'max'],
      //     style: {
      //       lineWidth: 1,
      //       stroke: '#A4A4A4'
      //     }
      //   });
      //   chart.guide().text({
      //     position: [obj.name, 'max'],
      //     content: moment(obj.name).format('YYYY-MM'),
      //     style: {
      //       textAlign: 'start',
      //       fill: '#cacaca',
      //       textBaseline: 'top'
      //     },
      //     offsetX: 5,
      //     offsetY: 5
      //   });
      // });
      // chart.interaction('pan');
      chart.render();
      // 配置柱状图点击交互
      // chart.interaction('interval-select', {
        // startEvent: 'touchstart'
        // selectAxisStyle: {
        //   fill: '#000',
        //   fontWeight: 'bold'
        // },
        // mode: 'range',
        // defaultSelected: {
        //   year: '1962 年',
        //   sales: 38
        // }
      // });
    }
  },
  beforeDestroy() {
    window.removeEventListener('scroll',this.debounceScroll, true)
  }
}
</script>

<style lang="less" scoped>

@color-block: #292E33;
@color-blue: #007AE6;
@color-gray: #919599;

.blue {
  color: @color-blue;
}
.block {
  color: @color-block;
}

.notData {
  margin: 160px auto;
  position: relative;
  .image-notData {
    width: 70px;
    height: 70px;
    margin: 0 auto;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
  }
  .floor-empty {
    background-image: url('../../../assets/img/dynamics/dataCountNull.png');
  }
  .data-empty {
    background-image: url('../../../assets/img/dynamics/dynamicsNull.png');
  }
  .text {
    color: #999;
    font-size: 12px;
    text-align: center;
  }
}

.inner {
  margin: 78px auto;
}


.dataContent {
  .charts {
    padding: 24px 0px 16px;
    background: #fff;
    .chart-title {
      padding: 16px 16px 0;
      font-size: 12px;
      color: @color-block;
    }
  }
  .progress-box {
    padding: 20px 0 30px;
    background: #fff;
    font-size: 14px;
    .progressList {
      padding: 0 16px;
      .progress-title {
        padding: 16px 0;
        font-size: 12px;
        color: @color-block;
      }
    }
  }
  .dataList {
    padding-top: 24px;
    .data-card {
      display: flex;
      padding-top: 12px;
      padding-bottom: 24px;
      .item-card {
        flex: 1;
        text-align: center;
        .number {
          font-size: 28px;
          font-weight: bold;
          font-family: 'DINCondensed-Bold';
        }
        .text-min {
          font-size: 12px;
          padding-top: 2px;
          transform: scale(0.8);
          color: @color-gray;
          // font-family: 'DINCondensed-Bold';
        }
      }
    }
  }

  .loading {
    text-align: center;
    font-size: 12px;
    color: #aaa;
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -80%);
    p {
      margin-top: 10px;
    }
  }
  .line {
    margin: 0 16px;
    // height: 1px;
  }
  .line::after {
    // background: -webkit-linear-gradient(top, #E2E8EE 50%, transparent);
    background: #E2E8EE
  }
}

</style>

